package com.handpay.nocardpay.baselibrary.qualificationinfo.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by fplei on 2017/8/11.
 * 资质提交输入框【一键删除内容/输入非法字符控制】
 */
@SuppressLint("AppCompatCustomView")
public class QualificationEditView extends EditText implements View.OnFocusChangeListener, TextWatcher {
    //EditText右侧的删除按钮
    private Drawable mClearDrawable = null;
    private boolean hasFoucs;
    private int rightIcon = -1;
    //允许输入中文
    private boolean isAllowChinese = true;
    //允许输入字母
    private boolean isAllowEnglish = true;
    //允许输入数字
    private boolean isAllowNumber = true;
    //允许输入特殊字符
    private boolean isAllowSpecialCharacters = true;
    //允许输入最大长度，默认-1 表示不限制
    private int allowMaxLenght = -1;

    public QualificationEditView(Context context) {
        this(context, null);
        init();
    }

    public QualificationEditView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
        getAttrs(context, attrs);
        init();
    }

    public QualificationEditView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        getAttrs(context, attrs);
        init();
    }

    private void getAttrs(Context context, AttributeSet attrs) {
        TypedArray mystyle = context.obtainStyledAttributes(attrs, R.styleable.QualificationEditView);
        try {
            if (mystyle != null) {
                rightIcon = mystyle.getResourceId(R.styleable.QualificationEditView_rightDeleteIcon, -1);
                isAllowChinese = mystyle.getBoolean(R.styleable.QualificationEditView_isAllowChinese, true);
                isAllowEnglish = mystyle.getBoolean(R.styleable.QualificationEditView_isAllowEnglish, true);
                isAllowNumber = mystyle.getBoolean(R.styleable.QualificationEditView_isAllowNumber, true);
                isAllowSpecialCharacters = mystyle.getBoolean(R.styleable.QualificationEditView_isAllowSpecialCharacters, true);
                allowMaxLenght = mystyle.getInteger(R.styleable.QualificationEditView_allowMaxLenght, -1);
                HPLog.i(HPLog.LFP_TAG, "allowMaxLenght:" + allowMaxLenght);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mystyle.recycle();
        }
    }

    private void init() {
        // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,获取图片的顺序是左上右下（0,1,2,3,）
        checkDrawable();
        // 默认设置隐藏图标
        setClearIconVisible(false);
        // 设置焦点改变的监听
        setOnFocusChangeListener(this);
        // 设置输入框里面内容发生改变的监听
        addTextChangedListener(this);
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (allowMaxLenght != -1) {//如果有设置最大输入值
                    if (((end - start) + dend) > allowMaxLenght) {
                        return "";
                    }
                }
                for (int i = start; i < end; i++) {
                    if (!isAllowChinese) {//不允许输入中文
                        if (isChinese(source.charAt(i))) {//判断是中文直接返回空字符串
                            return "";
                        }
                    }
                    if (!isAllowEnglish) {//不允许输入字母
                        if (isEnglish(source.charAt(i))) {
                            return "";
                        }
                    }
                    if (!isAllowNumber) {//不允许输入数字
                        if (isNumber(source.charAt(i))) {
                            return "";
                        }
                    }
                    if (!isAllowSpecialCharacters) {//不允许输入特殊字符和空格
                        if (isSpecialCharacters(source.toString())) {
                            return "";
                        }
                    }
                }
                return null;
            }
        };
        this.setFilters(new InputFilter[]{filter});
        this.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    //if input the key of enter(that no allowed),we will return true
                    return true;
                }
                return false;
            }
        });
    }

    public void setRightIcon(int mRightIcon) {
        this.rightIcon = mRightIcon;
    }

    private void checkDrawable() {
        try {
            if (rightIcon != -1) {
                mClearDrawable = getCompoundDrawables()[2];
                if (mClearDrawable == null) {
                    mClearDrawable = getResources().getDrawable(rightIcon);
                }
                Double width = (double) mClearDrawable.getIntrinsicWidth() / 1.5;
                Double height = (double) mClearDrawable.getIntrinsicHeight() / 1.5;
                mClearDrawable.setBounds(0, 0, width.intValue(), height.intValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /* @说明：isInnerWidth, isInnerHeight为ture，触摸点在删除图标之内，则视为点击了删除图标
     * event.getX() 获取相对应自身左上角的X坐标
     * event.getY() 获取相对应自身左上角的Y坐标
     * getWidth() 获取控件的宽度
     * getHeight() 获取控件的高度
     * getTotalPaddingRight() 获取删除图标左边缘到控件右边缘的距离
     * getPaddingRight() 获取删除图标右边缘到控件右边缘的距离
     * isInnerWidth:
     *  getWidth() - getTotalPaddingRight() 计算删除图标左边缘到控件左边缘的距离
     *  getWidth() - getPaddingRight() 计算删除图标右边缘到控件左边缘的距离
     * isInnerHeight:
     *  distance 删除图标顶部边缘到控件顶部边缘的距离
     *  distance + height 删除图标底部边缘到控件顶部边缘的距离
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                Rect rect = getCompoundDrawables()[2].getBounds();
                int height = rect.height();
                int distance = (getHeight() - height) / 2;
                boolean isInnerWidth = x > (getWidth() - getTotalPaddingRight()) && x < (getWidth() - getPaddingRight());
                boolean isInnerHeight = y > distance && y < (distance + height);
                if (isInnerWidth && isInnerHeight) {
                    this.setText("");
                }
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 当ClearEditText焦点发生变化的时候，
     * 输入长度为零，隐藏删除图标，否则，显示删除图标
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucs = hasFocus;
        if (hasFocus) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
    }

    public void setClearIconVisible(boolean visible) {
        if (mClearDrawable != null) {
            Drawable right = visible ? mClearDrawable : null;
            setCompoundDrawables(getCompoundDrawables()[0],
                    getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
        if (hasFoucs) {
            setClearIconVisible(s.length() > 0);
        }
    }

    /**
     * 设置无法更新编辑值
     */
    public void setCanNotUpdate(){
        this.clearFocus();
        this.setClearIconVisible(false);
        this.setFocusable(false);
        this.setEnabled(false);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */
    public boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为字母（大些或小写）
     *
     * @param c
     * @return
     */
    private boolean isEnglish(char c) {
        int mid = c;
        if (mid >= 65 && mid <= 90) {//大写字母
            return true;
        }
        if (mid >= 97 && mid <= 122) {//小写字母
            return true;
        }
        return false;
    }

    /**
     * 判断是否为数字
     *
     * @param c
     * @return
     */
    private boolean isNumber(char c) {
        int mid = c;
        if (mid >= 48 && mid <= 57) {//数字
            return true;
        }
        return false;
    }

    /**
     * 特殊字符（一般特殊字符和空格）
     *
     * @param c
     * @return
     */
    private boolean isSpecialCharacters(String c) {
        String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(speChat);
        Matcher matcher = pattern.matcher(c);
        if (" ".equals(c)) {
            return true;
        }
        if (matcher.find()) {
            return true;
        }
        return false;
    }

}
